﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.Model.VM.Org;

namespace Jinjia.Approve.Service.JJFlow.Approvers
{
    public class JJApproversCommon
    {
        protected readonly IJJApproversRepository _jjApproversRepository;

        public JJApproversCommon(IJJApproversRepository jjApproversRepository)
        {
            _jjApproversRepository = jjApproversRepository;
        }

        protected async Task<OrgStructure> GetOrgStructure(int user_id)
        {
            var userNode = await _jjApproversRepository.GetOrgNodeByUserId(user_id);
            if (userNode == null)
                return new OrgStructure();
            await GetOrgUpperNodes(userNode);

            return userNode;
        }

        /// <summary>
        /// 获取上级部门及部门leader
        /// </summary>
        private async Task GetOrgUpperNodes(OrgStructure org)
        {
            if (org == null)
                return;
            org.upperDept = await _jjApproversRepository.GetOrgNodeByNodeId(org.node_id);
            org.deptLink = new List<string>();

            foreach (var dept in org.upperDept)
            {
                //递归 获取上层节点
                dept.leaderNode = await _jjApproversRepository.GetOrgLeaderNodeByNodeId(dept.node_id);
                await GetOrgUpperNodes(dept);
                //拼接部门链路
                foreach (var link in dept.deptLink)
                {
                    org.deptLink.Add(link + "-" + org.user_name);
                }
            }

            if (org.deptLink.Count == 0)
                org.deptLink.Add(org.user_name);
        }
    }
}